//
//  WmcPhotoLayoutAlertView.swift
//  YPWatermarkCamera
//
//  Created by Json on 2023/8/1.
//

import UIKit
import RxRelay

class WmcPhotoLayoutAlertView: WmcBaseView, WmcAlertViewProtocol {

    /// stackView
    private lazy var stackView: UIStackView = {
        let stackV = UIStackView()
        stackV.axis = .vertical
        stackV.spacing = 18.0.wmc_autoHor
        stackV.distribution = .fill
        stackV.alignment = .fill
        return stackV
    }()
    /// 模板
    private lazy var templateView: WmcAlertTemplateGroupView = {
        let view = WmcAlertTemplateGroupView()
        return view
    }()
    /// 排列方式
    private lazy var layoutView: WmcAlertLayoutGroupView = {
        let view = WmcAlertLayoutGroupView()
        return view
    }()
    /// 设置
    private lazy var settingView: WmcAlertSettingGroupView = {
        let view = WmcAlertSettingGroupView()
        return view
    }()
    
    /// 更多功能按钮
    private lazy var moreButton: WmcStyleButton = {
        let button = WmcStyleButton(style: .imageRight, space: 0.0)
        button.setTitle("更多功能", for: .normal)
        button.setTitleColor(UIColor.wmc_mainTheme, for: .normal)
        button.setImage("arrow_right".wmc_image(tintColor: UIColor.wmc_mainTheme), for: .normal)
        button.titleLabel?.font = 13.wmc_scaleFont(weight: .medium)
        button.imageHeight = 10.0.wmc_autoHor
        return button
    }()
    
    /// 关闭按钮
    private lazy var closeButton: UIButton = {
        let button = UIButton()
        button.setImage("close".wmc_image, for: .normal)
        return button
    }()
    
    /// 模板样式
    var templateStyle: WmcPhotoTemplate.Style = .default {
        didSet {
            templateView.style = templateStyle
        }
    }

    /// 排版列数
    var layoutColumns: WmcPhotoLayout.Columns = .one {
        didSet {
            // 排版
            layoutView.columns = layoutColumns
            // 照片数量
            settingView.number = layoutView.selectedLayout?.photoNum ?? 2
        }
    }
    
    /// 已拍摄照片数量
    var finishedPhotoCount: Int = 0
    
    /// 最大数量
    var maxNum: Int = 20
    
    /// 最小数量
    var minNum: Int = 2
    
    /// 点击更多
    let moreAction: PublishRelay<Void> = .init()
    
    /// 选中排版回调
    let didSelectedLayout: PublishRelay<WmcPhotoLayout.Columns> = .init()
    
    /// 选中模板回调
    let didSelectedTemplate: PublishRelay<WmcPhotoTemplate.Style> = .init()
    
    /// 照片数量变化回调
    let photoNumChanged: PublishRelay<Int> = .init()
    
    
    // MARK: UI
    override func makeUI() {
        super.makeUI()
        let hMargin = 16.0.wmc_autoHor
        let vMargin = 20.0.wmc_autoHor
        layer.cornerRadius = 12.0
        layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        clipsToBounds = true
        // stackView
        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.top.equalTo(vMargin)
            make.left.equalTo(hMargin)
            make.right.equalTo(-hMargin)
        }
        // 模板
        stackView.addArrangedSubview(templateView)
        // 排列
        stackView.addArrangedSubview(layoutView)
        // 设置
        stackView.addArrangedSubview(settingView)
        // 更多功能按钮
        addSubview(moreButton)
        moreButton.snp.makeConstraints { make in
            make.top.equalTo(stackView.snp.bottom).offset(vMargin)
            make.centerX.equalToSuperview()
            make.width.equalTo(80.0.wmc_autoHor)
            make.height.equalTo(20.0.wmc_autoHor)
            make.bottom.equalTo(-Wmc_safeAreaBottom-vMargin)
        }
        // 关闭按钮
        addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.width.height.equalTo(30.0.wmc_autoHor)
            make.right.equalTo(-12.0.wmc_autoHor)
            make.top.equalTo(12.0.wmc_autoHor)
        }
    }
    
    // MARK: Bind Action
    override func bindViewAction() {
        super.bindViewAction()
        // 点击关闭
        closeButton.rx.tap.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.dismiss()
        }).disposed(by: rx.disposeBag)
        // 点击更多功能
        moreButton.rx.tap.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.dismiss {
                [weak self] in
                guard let self = self else { return }
                self.moreAction.accept(())
            }
        }).disposed(by: rx.disposeBag)
        // 选中模板回调
        templateView.didSelectedTemplate.subscribe(onNext: {
            [weak self] template in
            guard let self = self else { return }
            self.didSelectedTemplate.accept(template.style)
        }).disposed(by: rx.disposeBag)
        
        // 选中排版回调
        layoutView.didSelectedLayout.subscribe(onNext: {
            [weak self] layout in
            guard let self = self else { return }
            if self.finishedPhotoCount >= layout.photoNum { // 如果已拍摄照片已达到当前排版的最大数量,则将当前排版照片数量加1
                let photoNum = self.finishedPhotoCount + 1
                self.update(photoNum: photoNum, layout: layout)
            }
            // 排版选择回调
            self.didSelectedLayout.accept(layout.columns)
            // 更新照片数量UI
            self.settingView.number = layout.photoNum
            // 回调
            self.photoNumChanged.accept(layout.photoNum)
        }).disposed(by: rx.disposeBag)
        
        // 点击加号
        settingView.addAction.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            let number = self.settingView.number
            if number >= self.maxNum {
                WmcHudManager.toast("最多可拼\(self.maxNum)图片")
                return
            }
            // 照片数加1
            let new_number = number + 1
            self.didChanged(photoNum: new_number)
            
        }).disposed(by: rx.disposeBag)
        
        // 点击减号
        settingView.minusAction.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            let number = self.settingView.number
            if number <= self.minNum {
                WmcHudManager.toast("最少需拼\(self.minNum)图片")
                return
            }
            // 照片数减一
            let new_number = number - 1
            if new_number <= self.finishedPhotoCount {
                WmcHudManager.toast("已拍摄\(self.finishedPhotoCount)张图片，无法再减少")
                return
            }
            self.didChanged(photoNum: new_number)
        }).disposed(by: rx.disposeBag)
    }

}

extension WmcPhotoLayoutAlertView {
    
    /// 更新某个排版对应的照片数量
    /// - Parameters:
    ///   - photoNum: 照片数量
    ///   - layout: 排版
    private func update(photoNum: Int, layout: WmcPhotoLayout) {
        // 更新数据
        layout.photoNum = photoNum
        WmcUserdefault.save(value: photoNum, forKey: .State.CombinePhoto.layoutPhotoNum, associateValue: "\(layout.columns.rawValue)")
    }
    /// 照片数量变化后调用
    private func didChanged(photoNum: Int) {
        // 更新当前排版对应的照片数量
        if let layout = layoutView.selectedLayout {
            update(photoNum: photoNum, layout: layout)
        }
        // 更新照片数量UI
        settingView.number = photoNum
        // 回调
        photoNumChanged.accept(photoNum)
    }
}
